package com.coocaa.x.service.litewebserver.webserver;

import android.content.Context;
import com.coocaa.x.service.litewebserver.webserver.servlet.Servlet;
import com.coocaa.x.service.litewebserver.webserver.servlet.ServletManager;

import java.io.IOException;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

/**
 * Created by lu on 15-9-7.
 */
public class LiteWebHttpd extends NanoHTTPD {

    public static interface ServletHandler {
        Response serve(IHTTPSession session);
    }

    private static LiteWebHttpd httpd = null;

    public static LiteWebHttpd getHttpd() {
        return httpd;
    }

    private static final String URL_FORMAT = "http://%s:%d";
    private Context mContext = null;

    public LiteWebHttpd(Context context, int port) {
        super(port);
        mContext = context;//CoocaaApplication.getContext();
        httpd = this;
    }

    public String getURL() {
        return String.format(URL_FORMAT, getLocalIPAddress(), getListeningPort());
    }

    @Override
    public void start(int timeout, boolean daemon) throws IOException {
        ServletManager.getManager(mContext).start();
        super.start(timeout, daemon);
    }

    @Override
    public void stop() {
        super.stop();
        ServletManager.getManager(mContext).stop();
    }

    @Override
    public Response serve(IHTTPSession session) {
        String uri = null;
        try {
            uri = session.getUri();
            Servlet s = ServletManager.getManager(mContext).getServlet(uri);
            if (s != null)
                return s.serve(session);
        } catch (Exception e) {
            return newFixedLengthResponse(e.getMessage() + "\n     All my fault!\n        --李大爷");
        }
        return newFixedLengthResponse(uri + " not support!!");
    }

    public static String getLocalIPAddress() {
        try {
            Enumeration allNetInterfaces = NetworkInterface.getNetworkInterfaces();
            InetAddress ip = null;
            while (allNetInterfaces.hasMoreElements()) {
                NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
                System.out.println(netInterface.getName());
                Enumeration addresses = netInterface.getInetAddresses();
                while (addresses.hasMoreElements()) {
                    ip = (InetAddress) addresses.nextElement();
                    if (ip != null && ip instanceof Inet4Address && !ip.getHostAddress().toString().contains("127.0.0.1")) {
                        System.out.println("本机的IP = " + ip.getHostAddress());
                        return ip.getHostAddress();
                    }
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }
        return "";
    }
}
